#include <stdlib.h>
#include <unistd.h>
#include "z_logger.h"
#include "vector.h"
#include "aliot.h"
#include "service.h"
#include "sqlite.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"

int main(int argc, char *argv[]) {
    int32_t res = STATE_SUCCESS;

    extern aiot_sysdep_portfile_t g_aiot_sysdep_portfile;
    aiot_sysdep_set_portfile(&g_aiot_sysdep_portfile);
    aiot_state_set_logcb(aliot_state_log_cb);

    log_init();

    seqiot_t *seqiot = seqiot_new();
    read_config(seqiot, NULL, 0, 0);

    aiot_sysdep_network_cred_t cred;
    aliot_set_cred(&cred);

    aliot_service_args_t service_args = {
            .mqtt_handle = NULL,
            .cred = &cred,
            .seqiot =seqiot,
    };

    aliot_service_t *mqtt_service = mqtt_service_get();
    service_args.mqtt_handle = mqtt_service->init(&service_args);

    res = aiot_mqtt_connect(service_args.mqtt_handle);
    if (aliot_error_check("aiot_mqtt_connect", res) < 0) {
        goto err;
    }

    vector_t service_list = vector_initializer;
    vector_add(&service_list, ota_service_get());
//    vector_add(&service_list, ntp_service_get());
//    vector_add(&service_list, ra_service_get());
//    vector_add(&service_list, devinfo_service_get());
//    vector_add(&service_list, subdev_service_get());
//    vector_add(&service_list, dm_service_get());
//    vector_add(&service_list, logpost_service_get());
//    vector_add(&service_list, upload_service_get());
//    vector_add(&service_list, pub_service_get());

    for (int i = 0; i < vector_size(&service_list); ++i) {
        aliot_service_t *service = vector_get(&service_list, i);
        service->args = &service_args;
    }

    //mqtt start 接收函数
    mqtt_service->handle = service_args.mqtt_handle;
    aliot_mqtt_start(mqtt_service);

    vector_foreach(&service_list, (vector_foreach_callback) aliot_service_start);

    aliot_process_thread(service_args.mqtt_handle);

    vector_foreach_r(&service_list, (vector_foreach_callback) aliot_service_stop);

    aiot_mqtt_disconnect(&service_args.mqtt_handle);

    err:
    mqtt_service->fini(&service_args.mqtt_handle);
    seqiot_free(seqiot);
    log_fini();

    return EXIT_SUCCESS;
}
